//
//  BonjourListenerSensor.m
//  Pennyworth
//
//  Created by Chris Karr on 7/5/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "BonjourListenerSensor.h"
#import "AppDelegate.h"

#define SERVICE @"_pennyworth._tcp."

@implementation BonjourListenerSensor

@synthesize bonjour;
@synthesize task;

- (NSString *) machineName
{
	CFStringRef nameRef;
	NSString * computerName;
	nameRef = CSCopyMachineName ();
	computerName = [NSString stringWithString:(NSString *) nameRef];
	CFRelease (nameRef);
	
	return computerName;
}

- (void) stopServer
{
	[self.bonjour release];
	self.bonjour = nil;

	[self.task interrupt];
	self.task = nil;
}

- (void) startServer
{
	if (self.bonjour != nil)
		[self stopServer];

	NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

	NSString * port = [defaults stringForKey:@"Bonjour_Port"];
	
	if (port == nil)
		port = @"12345";
	
	self.bonjour = [[NSNetService alloc] initWithDomain:@"local" type:SERVICE name:[self machineName] port:[port intValue]];
	[self.bonjour publish];

	NSString * pythonPath = [[NSBundle mainBundle] pathForResource:@"Bonjour Server" ofType:@"py"];

	NSString * key = [defaults stringForKey:@"Bonjour_Key"];
	if (key == nil)
		key = @"abc123";
	
	// NSLog (@"%@ %@ %@", pythonPath, port, key);
	
	self.task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/python" arguments:[NSArray arrayWithObjects: pythonPath, port, key, nil]];
}

- (void) awakeFromNib
{
	NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
	
	if ([defaults boolForKey:@"Bonjour_Listener"])
		[self startServer];
	
	[defaults addObserver:self forKeyPath:@"Bonjour_Listener" options:0 context:NULL];
	[defaults addObserver:self forKeyPath:@"Bonjour_Key" options:0 context:NULL];
	[defaults addObserver:self forKeyPath:@"Bonjour_Port" options:0 context:NULL];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quit:) name:TERMINATE_NOTIFICATION object:nil];
}

- (void) observeValueForKeyPath:(NSString *) keyPath ofObject:(id) object change:(NSDictionary *) change context:(void *) context
{
	[self stopServer];

	NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
	
	if ([defaults boolForKey:@"Bonjour_Listener"])
		[self startServer];
}

- (void) quit:(NSNotification *) theNote
{
	[self stopServer];
}

@end
